package com.pethospital.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pethospital.common.Result;
import com.pethospital.dto.AppointmentDTO;
import com.pethospital.entity.Appointment;
import com.pethospital.service.AppointmentService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预约控制器
 */
@RestController
@RequestMapping("/appointment")
public class AppointmentController {

    @Resource
    private AppointmentService appointmentService;
    
    @Resource
    private ObjectMapper objectMapper; // 注入已配置好的ObjectMapper

    /**
     * 创建预约
     */
    @PostMapping
    public Result<Long> createAppointment(@RequestBody @Valid AppointmentDTO appointmentDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        Long appointmentId = appointmentService.createAppointment(appointmentDTO, userId);
        return Result.success(appointmentId);
    }

    /**
     * 取消预约
     */
    @PostMapping("/cancel/{id}")
    public Result<Void> cancelAppointment(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        appointmentService.cancelAppointment(id, userId);
        return Result.success();
    }

    /**
     * 完成预约
     */
    @PostMapping("/complete/{id}")
    public Result<Void> completeAppointment(@PathVariable Long id, HttpServletRequest request) {
        Long staffId = (Long) request.getAttribute("userId");
        appointmentService.completeAppointment(id, staffId);
        return Result.success();
    }

    /**
     * 获取预约详情
     */
    @GetMapping("/{id}")
    public Result<Appointment> getAppointment(@PathVariable Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        System.out.println("获取预约详情, id: " + id + ", userId: " + userId);
        
        Appointment appointment = appointmentService.getAppointment(id, userId);
        
        // 打印所有字段值，包括辅助字段
        System.out.println("Appointment id: " + appointment.getId());
        System.out.println("Appointment userId: " + appointment.getUserId());
        System.out.println("Appointment petId: " + appointment.getPetId());
        System.out.println("Appointment petName: " + appointment.getPetName());
        System.out.println("Appointment staffId: " + appointment.getStaffId());
        System.out.println("Appointment staffName: " + appointment.getStaffName());
        System.out.println("Appointment departmentId: " + appointment.getDepartmentId());
        System.out.println("Appointment departmentName: " + appointment.getDepartmentName());
        System.out.println("Appointment type: " + appointment.getType());
        System.out.println("Appointment status: " + appointment.getStatus());
        System.out.println("Appointment appointmentTime: " + appointment.getAppointmentTime());
        System.out.println("Appointment description: " + appointment.getDescription());
        System.out.println("Appointment remark: " + appointment.getRemark());
        System.out.println("Appointment review: " + appointment.getReview());
        
        // 检查extraData字段
        if (appointment.getExtraData() != null) {
            System.out.println("extraData size: " + appointment.getExtraData().size());
            for (Map.Entry<String, Object> entry : appointment.getExtraData().entrySet()) {
                System.out.println("extraData字段: " + entry.getKey() + " = " + entry.getValue());
            }
        } else {
            System.out.println("extraData为空");
        }
        
        // 手动构建一个HashMap来测试是否能正确传递到前端
        HashMap<String, Object> testData = new HashMap<>();
        testData.put("id", appointment.getId());
        testData.put("userId", appointment.getUserId());
        testData.put("petId", appointment.getPetId());
        testData.put("staffId", appointment.getStaffId());
        testData.put("departmentId", appointment.getDepartmentId());
        testData.put("appointmentTime", appointment.getAppointmentTime());
        testData.put("type", appointment.getType());
        testData.put("description", appointment.getDescription());
        testData.put("remark", appointment.getRemark());
        testData.put("status", appointment.getStatus());
        testData.put("createTime", appointment.getCreateTime());
        testData.put("updateTime", appointment.getUpdateTime());
        
        // 添加辅助字段
        testData.put("petName", appointment.getPetName() != null ? appointment.getPetName() : "测试宠物名称");
        testData.put("staffName", appointment.getStaffName() != null ? appointment.getStaffName() : "测试医生名称");
        testData.put("departmentName", appointment.getDepartmentName() != null ? appointment.getDepartmentName() : "测试科室名称");
        
        // 转为JSON字符串进行测试
        try {
            String jsonStr = objectMapper.writeValueAsString(testData);
            System.out.println("测试数据JSON: " + jsonStr);
            
            // 同样测试appointment对象
            String appointmentJson = objectMapper.writeValueAsString(appointment);
            System.out.println("Appointment对象JSON: " + appointmentJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return Result.success(appointment);
    }

    /**
     * 获取用户预约列表
     */
    @GetMapping("/user")
    public Result<Page<Appointment>> getUserAppointments(
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        Page<Appointment> appointments = appointmentService.getUserAppointments(userId, status, page, size);
        return Result.success(appointments);
    }

    /**
     * 获取医护人员预约列表
     */
    @GetMapping("/staff")
    public Result<Page<Appointment>> getStaffAppointments(
            @RequestParam(defaultValue = "0") Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        Long staffId = (Long) request.getAttribute("userId");
        Page<Appointment> appointments = appointmentService.getStaffAppointments(staffId, status, page, size);
        return Result.success(appointments);
    }

    /**
     * 确认预约（医护人员操作）
     */
    @PostMapping("/confirm/{id}")
    public Result<Void> confirmAppointment(@PathVariable Long id, HttpServletRequest request) {
        Long staffId = (Long) request.getAttribute("userId");
        appointmentService.confirmAppointment(id, staffId);
        return Result.success();
    }
    
    /**
     * 拒绝预约（医护人员操作）
     */
    @PostMapping("/reject/{id}")
    public Result<Void> rejectAppointment(@PathVariable Long id, HttpServletRequest request) {
        Long staffId = (Long) request.getAttribute("userId");
        appointmentService.rejectAppointment(id, staffId);
        return Result.success();
    }

    /**
     * 获取医护人员今日预约
     */
    @GetMapping("/staff/today")
    public Result<List<Appointment>> getStaffTodayAppointments(HttpServletRequest request) {
        Long staffId = (Long) request.getAttribute("userId");
        List<Appointment> appointments = appointmentService.getStaffTodayAppointments(staffId);
        return Result.success(appointments);
    }

    /**
     * 获取医护人员预约统计
     */
    @GetMapping("/staff/statistics")
    public Result<Map<String, Object>> getStaffAppointmentStatistics(HttpServletRequest request) {
        Long staffId = (Long) request.getAttribute("userId");
        Map<String, Object> statistics = appointmentService.getStaffAppointmentStatistics(staffId);
        return Result.success(statistics);
    }

    /**
     * 获取预约详情（含评价信息）
     */
    @GetMapping("/detail/{id}")
    public Result<com.pethospital.vo.AppointmentVO> getAppointmentDetail(@PathVariable Long id) {
        System.out.println("获取预约详情(detail) - ID: " + id);
        com.pethospital.vo.AppointmentVO appointmentVO = appointmentService.getAppointmentDetail(id);
        if (appointmentVO == null) {
            return Result.error("预约不存在");
        }
        
        // 打印详细信息
        System.out.println("预约详情 - ID: " + appointmentVO.getId());
        System.out.println("预约用户信息 - UserID: " + appointmentVO.getUserId() + ", UserName: " + appointmentVO.getUserName());
        System.out.println("预约宠物信息 - PetID: " + appointmentVO.getPetId() + ", PetName: " + appointmentVO.getPetName());
        System.out.println("预约医生信息 - StaffID: " + appointmentVO.getStaffId() + ", StaffName: " + appointmentVO.getStaffName());
        
        // 确保userName不为空
        if (appointmentVO.getUserName() == null || appointmentVO.getUserName().isEmpty()) {
            // 如果为空，可以设置一个默认值或使用用户ID
            appointmentVO.setUserName("用户" + appointmentVO.getUserId());
            System.out.println("已设置默认用户名: " + appointmentVO.getUserName());
        }
        
        return Result.success(appointmentVO);
    }
} 